package com.oswift.utils.common;

import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;

/**
 *
 * 获取图片的分辨率及高和宽px
 *
 * @author zhuou
 * @version C03 2013-10-23
 * @since OSwift GPM V1.0
 */
public class ImageResolution
{
    /**
     * 获取图片的分辨率
     *
     * @param path
     * @return Dimension
     */
    public static Dimension getImageDim(String path)
    {
        Dimension result = null;
        String suffix = getFileSuffix(path);

        // 解码具有给定后缀的文件
        Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
        if (iter.hasNext())
        {
            ImageReader reader = iter.next();
            try
            {
                ImageInputStream stream = new FileImageInputStream(new File(
                        path));
                reader.setInput(stream);
                int width = reader.getWidth(reader.getMinIndex());
                int height = reader.getHeight(reader.getMinIndex());
                result = new Dimension(width, height);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            finally
            {
                reader.dispose();
            }
        }
        return result;
    }

    /**
     * 获得图片的后缀名
     *
     * @param path
     *            图片路径
     * @return 图片后缀
     */
    private static String getFileSuffix(final String path)
    {
        String result = null;
        if (path != null)
        {
            result = "";
            if (path.lastIndexOf('.') != -1)
            {
                result = path.substring(path.lastIndexOf('.'));
                if (result.startsWith("."))
                {
                    result = result.substring(1);
                }
            }
        }
        return result;
    }
}
